import os
import requests
import time
import zipfile


def download_and_unzip(url, path):
    if not os.path.exists(path):
        os.mkdir(path)
    file_path = os.path.join(path, 'case11Fiveflowers.zip')
    start = time.time()
    user, password = 'tyx_neu', 'Sportlab307'
    resp = requests.get(url, auth=(user, password), stream=True)
    size = 0
    chunk_size = 1024
    content_size = int(resp.headers['content-length'])
    try:
        if resp.status_code == 200:
            print('start download ,[File size]:{size:.2f} MB'.format(size=content_size / chunk_size / 1024))
            with open(file_path, 'wb') as file:
                for data in resp.iter_content(chunk_size=chunk_size):
                    file.write(data)
                    size += len(data)
                    print('\r' + '[下载进度]:%s%.2f%%' % (
                        '>' * int(size * 50 / content_size), float(size / content_size * 100)), end=' ')
        end = time.time()
        print('\n' + 'Download completed! times:%.2f秒' % (end - start))
    except ValueError:
        print('Error')

    unzip_file_path = os.path.join(path, 'case11Fiveflowers')
    if not os.path.exists(unzip_file_path):
        os.mkdir(unzip_file_path)
    zip_file = zipfile.ZipFile(file_path)
    zip_list = zip_file.namelist()
    for f in zip_list:
        zip_file.extract(f, unzip_file_path)
    zip_file.close()
    print('Successfully unzip download dataset from website!')


url = "https://openi.pcl.ac.cn/attachments/0405d976-18a7-46b1-81d2-9ccad3b722ae?type=1"
download_and_unzip(url, os.path.join(os.getcwd(), 'dataset'))


